<?php

namespace common\logics\cascader;

use Yii;
use common\helpers\ArrayHelper;
use common\models\shop\ShopStoreCategory;
use common\models\shop\ShopCategory;

/**
 * 级联选择器
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class StoreCategoryLogic extends ShopStoreCategory {

    /**
     * @param integer $pid
     * @param boolean $deeps
     * @return \common\db\ActiveQuery
     */
    public static function findDeepsOfStoreId($storeId = 0) {
        if (!$storeId) {
            return [];
        }
        $storeCategorys = static::find()->active(static::STATUS_ACTIVE)->andFilterWhere([
            'store_id' => $storeId,
        ])->all();
        $ids = ArrayHelper::getColumn($storeCategorys, 'category_id');
        foreach ($storeCategorys as $storeCategory) {
            $category = $storeCategory->category;
            $parent = $category->parent;
            while ($parent) {
                $ids[] = $parent->id;
                $parent = $parent->parent;
            }
        }
        $query = ShopCategory::find()->alias('t')->active(ShopCategory::STATUS_ACTIVE);
        $query->andWhere([
            't.id' => $ids
        ]);
        $categories = $query->all();
        return ArrayHelper::toTree($categories);
    }

}
